<template>
	<div class="protocol-manager-info">
		<div class="main_content">
			<div class="main_content_title">
				<div class="left">
					<span>{{ propUpType === 'add' ? $t('publicBtn.add') : propUpType === 'edit' ? $t('publicBtn.edit') :
						$t('publicBtn.detail') }}</span>
					<template v-for="(item, index) in $route.meta.title">
						<span v-if="languageId === item.langId">{{ item.name }}</span>
					</template>
				</div>
				<div class="right" />
			</div>
			<div class="main_content_con">
				<!-- 语言动态标签页面 -->
				<el-row :gutter="24">
					<el-col :span="14">
						<elTabPane :isShow="isTag" :tagId="tagId" @tagClick="tagClick"></elTabPane>
					</el-col>
				</el-row>
				<el-form ref="info" :model="info" :rules="rules" class="demo-ruleForm">
					<el-form v-for="(info, index) in info.list" :ref="`info${index}`" :model="info" :rules="rules"
						v-show="tagId === info.langId" :key="index" label-width="110px" class="demo-ruleForm">
						<div class="content_info">
							<template v-if="propUpType === 'add' || propUpType === 'edit'">
								<el-row :gutter="24">
									<el-col :span="8">
										<el-form-item :label="$t('publicFormLabel.name')" prop="name">
											<el-input v-model="info.name" :placeholder="$t('placeholderTip.enter')" />
										</el-form-item>
									</el-col>
									<el-col :span="8">
										<el-form-item :label="$t('publicFormLabel.type')" prop="type">
											<el-select v-model="info.type" @change="copyValue('list', 'type', info.type)"
												:placeholder="$t('placeholderTip.pSelect')" style="width:100%">
												<el-option v-for="item in $t('agreementTypeList')" :key="item.type" :label="item.name"
													:value="item.type" />
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
							</template>
							<template v-else>
								<el-row :gutter="24">
									<el-col :span="8">
										<el-form-item :label="$t('publicFormLabel.name')" prop="name">
											<el-input readonly :value="info.name" />
										</el-form-item>
									</el-col>
									<el-col :span="8">
										<el-form-item :label="$t('publicFormLabel.type')" prop="type">
											<el-select :disabled="true" :value="info.type" style="width:100%">
												<el-option v-for="item in $t('agreementTypeList')" :key="item.type" :label="item.name"
													:value="item.type" />
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
							</template>
							<div>
								<span style="font-size: 16px;color: #333;">{{ $t('text.dynamicFieldTitle') }} <span
										style="font-size: 14px;color: #909399;"></span>{{ $t('text.dynamicFieldTip') }}</span>
							</div>
							<div class="labelList">
								<div class="item" v-for="(item, index) in dynamicFieldList" :key="index">
									<div>
										{{ item.name }}
									</div>
									<div>{{ item.value }}</div>
								</div>
							</div>
							<div class="article_content">
								<Tinymce v-if="propUpType === 'detail'" :content="info.content" :settingData="setting" height="400" />
								<Tinymce v-if="showTinymce" :content="info.content"
									:on-message="function (res) { return messageInfo(res, info, 'content') }" :settingData="setting"
									height="400"></Tinymce>
							</div>
						</div>
					</el-form>
				</el-form>
				<div class="footerBtn">
					<el-button @click="getCancle">{{ propUpType !== 'detail' ? $t('el.popconfirm.cancelButtonText') :
						$t('el.popconfirm.close') }}</el-button>
					<el-button v-if="propUpType !== 'detail'" type="primary" @click="addSubmitForm"
						v-loading.fullscreen.lock="fullscreenLoading">{{ $t('el.popconfirm.confirmButtonText') }}</el-button>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
import {
	getDynamicFields,
	getAgreementInfo,
	setAgreementSave,
	setAgreementUpdate
} from '@/api/basics-manager'
import Tinymce from '@/components/VueTinymceUeditor/index.vue'
import elTabPane from '@/components/el-tab-pane/index'; //语言动态标签页面
export default {
	name: 'ProtocolManagerInfo',
	components: {
		Tinymce,
		elTabPane,
	},
	data() {
		return {

			info: {
				list: []
			},
			rules: {
				type: [
					{
						required: true,
						message: this.$t('placeholderTip.pSelect'),
						trigger: 'change'
					}
				],
				name: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				]
			},
			tagId: '',//语言id 默认id 
			isTag: false,
			showTinymce: false,
			setting: {
				menubar: true, // //是否显示菜单栏
				branding: true, //取消tinymce水印
				paste_word_valid_elements: '*[*]', //word粘贴使用
				paste_data_images: true, //// 默认是false的，记得要改为true才能粘贴
				images_file_types: 'jpeg,jpg,png,gif',
				toolbar_drawer: 'sliding', //工具栏过多，点击“...”打开抽屉过度效果
				plugins: [
					'lists',
					'code',
					'table',
					'formatselect',
					'colorpicker',
					'textcolor',
					'contextmenu',
					'preview',
					'fullscreen',
					'media',
					'link',
					'image',
					'paste'
				],
				toolbar:
					'undo redo | fullscreen | alignleft aligncenter alignright alignjustify |indent_use_margin bullist | image media table | styleselect | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | superscript subscript | removeformat | paste|'
			},
			propUpType: '', // 'add' edit detail
			fullscreenLoading: false,
			dynamicFieldList: [], //动态字段
			enterFlag: false,
			enterNumber: ''
		}
	},
	computed: {
		languageId() {
			// 固定语种ID  1:中文  2:英文 3:俄文 4:乌语
			return this.$store.getters.languageId
		},
		languageList() {
			return this.$store.getters.languageList.length > 0 ? this.$store.getters.languageList : JSON.parse(localStorage.getItem('languageList'))
		}
	},
	watch: {
		propUpType: function (val) {
			if (val !== 'detail') {
				var timer = setTimeout(() => {
					this.showTinymce = true
					window.clearTimeout(timer)
				}, 500)
			} else {
				this.showTinymce = false
			}
		}
	},
	mounted() {
		window._vm = this
		this.propUpType = this.$route.query.propUpType
		this.isTag = true;
		this.tagId = this.languageId;
		if (this.$route.query.propUpType === 'add') {
			this.$nextTick(() => (this.showTinymce = true))
			var arr = []
			this.languageList.map(i => {
				var obj = {
					langId: i.id,
					id: '',
					name: '', //协议名称--多语言
					type: '', //协议类型
					content: '' //内容--多语言
				}
				arr.push(obj)
			})
			this.info.list = arr
		} else if (this.$route.query.id) {
			this.getInfo(this.$route.query.id)
		}
		this.getDynamicFieldsData()
	},
	created() { },
	activated() {

	},
	destroyed() {
	},
	methods: {
		messageInfo(content, tar, key) {
			tar[key] = content
		},
		// 语言菜单处理
		tagClick(id) {
			if (id !== this.tagId) {
				this.resetForm('info', 2)
				this.tagId = id
			}
		},
		// 无多语言字段处理
		copyValue(key, key2, value) {
			this.info[key].map(i => {
				i[key2] = value
			})
		},
		// 重置表单
		resetForm(vaid, type) {
			// type 1 重置表单 2仅清空校验
			if (this.$refs[vaid] !== undefined) {
				this.$nextTick(() => {
					Promise.all([
						//数组部分的表单，用map返回验证函数的调用
						...this.info.list.map((item, index) => {
							var refs = `info${index}`
							let valiForm = this.$refs?.[refs].validate
								? this.$refs?.[refs]
								: this.$refs?.[refs][0];
							if (type === 1) {
								valiForm.resetFields()
							} else {
								valiForm.clearValidate()
							}
						})

					])
				})

			}
		},
		getDynamicFieldsData() {
			getDynamicFields().then(res => {
				if (res.code === 200) {
					this.dynamicFieldList = res.data
				}
			})
		},

		getCheck(index) {
			var list = JSON.parse(JSON.stringify(this.info.list))
			list.splice(index, 1)
			var falg1 = []
			for (var i = 0; i < list.length; i++) {
				var item = list[i]
				// 表单校验
				var name = ''
				// 多语言必填字段
				if (item.name && item.content) {
				} else if (item.name || item.content) {
					this.languageList.map(j => {
						if (j.id === item.langId) {
							name = j.name
						}
					})
					this.$message({
						showClose: true,
						message: name + ':' + this.$t('text.improveForms'),
						type: 'warning'
					})
					falg1.push(0)
					return false
				} else {
					falg1.push(1)
				}
			}
			var isallZeros = false
			// 判断是否包含0
			if (falg1.length > 0) {
				isallZeros = falg1.includes(0)
			}
			return !isallZeros
		},
		// 提交
		addSubmitForm() {
			var list = JSON.parse(JSON.stringify(this.info.list))
			var flag = false
			for (var i = 0; i < list.length; i++) {
				var item = list[i]
				var index = i
				// 当前语种 表单校验every
				if (this.tagId === item.langId) {
					console.log(index)
					let valiForm = this.$refs?.[`info${index}`].validate
						? this.$refs?.[`info${index}`]
						: this.$refs?.[`info${index}`][0];
					valiForm.validate((res) => {
						if (res) {
							flag = this.getCheck(index)
						} else {
							return false
						}
					})
				}
			}
			if (flag) {
				// 全部表单验证通过
				var arr = JSON.parse(JSON.stringify(this.info.list))
				this.fullscreenLoading = true
				if (this.propUpType === 'add') {
					setAgreementSave({
						t: arr
					})
						.then(res => {
							if (res.code === 200) {
								this.$message({
									showClose: true,
									message: this.$t('text.addSucceedTip'),
									type: 'success'
								})
								this.fullscreenLoading = false
								this.getCancle()
							}
						})
						.catch(err => {
							this.fullscreenLoading = false
						})

				} else {
					setAgreementUpdate({
						t: arr
					})
						.then(res => {
							if (res.code === 200) {
								this.$message({
									showClose: true,
									message: this.$t('text.editSucceedTip'),
									type: 'success'
								})
								this.fullscreenLoading = false
								this.getCancle()
							}
						})
						.finally(() => {
							this.fullscreenLoading = false
						})
				}
			}
		},
		// 详情
		getInfo(id) {
			const loading = this.$loading({
				lock: true,
				text: this.$t('text.loading'),
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			getAgreementInfo(id).then(res => {
				if (res.code === 200) {
					var arr = res.data.t || []
					if (arr.length > 0) {
						this.setInfoData(arr)
					}
					loading.close()
				}
			}).catch(() => {
				loading.close()
			})
		},
		// 详情数据处理
		setInfoData(data) {
			this.$nextTick(() => {
				var newArr = []
				var arr = data
				var newObj = arr[0]
				if (this.propUpType !== 'detail') {
					this.languageList.map(i => {
						var obj = {
							langId: i.id,
							id: newObj.id,
							name: '', //协议名称--多语言
							type: newObj.type, //协议类型
							content: '' //内容--多语言
						}
						newArr.push(obj)
					})
				} else {
					this.languageList.map(i => {
						var obj = {
							langId: i.id,
							id: '',
							name: '', //协议名称--多语言
							type: '', //协议类型
							content: '' //内容--多语言
						}
						newArr.push(obj)
					})
				}

				arr.map(j => {
					if (j.banner) {
						// 处理banner字段
						j.banner = j.banner.split(',')
					}
					// 根据id进行对象替换
					let index = newArr.findIndex(e =>
						e.langId == j.langId
					)
					if (index > -1) {
						newArr[index] = j
					}
				})
				this.info.list = newArr
			})
		},
		// 取消
		getCancle() {
			this.$store.state.tagsView.visitedViews.splice(
				this.$store.state.tagsView.visitedViews.findIndex(
					item => item.path === this.$route.path
				),
				1
			)
			this.$router.go(-1)
		}
	}
}
</script>
<style lang="scss" scoped>
.protocol-manager-info {
	height: 100%;
	width: 100%;
	padding: 20px;
	box-sizing: border-box;
	overflow: hidden;

	&>.main_content {
		width: 99.9%;
		height: 100%;

		&>.main_content_title {
			margin-bottom: 10px;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}

		.main_content_con {
			height: calc(100% - 40px);
			width: 100%;
			display: inline-block;
			border: 1px solid #dfe6ec;
			padding: 20px;

			&>.el-form {
				width: 100%;
				height: calc(100% - 108px);
				margin-top: 20px;
				overflow: hidden;

				&>.el-form {
					width: 100%;
					height: 100%;
				}

				&>.content_info {
					width: 100%;
					height: calc(100% - 40px);
					overflow: hidden;
					overflow-y: auto;
				}

				.labelList {
					display: flex;
					display: -webkit-flex;
					justify-content: flex-start;
					width: 100%;
					height: auto;
					flex-direction: row;
					flex-wrap: wrap;
					align-items: center;
					margin: 15px 0;

					&>.item {
						width: calc(25% - 20px);
						margin-right: 26px;
						border: 1px solid #dfe6ec;
						height: 40px;
						line-height: 40px;
						display: flex;
						justify-content: space-between;
						text-align: center;
						color: #333;
						font-size: 14px;

						&>div:nth-child(1) {
							width: 40%;
							padding: 0 10px;
							border-right: 1px solid #dfe6ec;
							box-sizing: border-box;
							overflow: hidden;
							white-space: nowrap;
							/*强制一行显示*/
							text-overflow: ellipsis;
							/*最后添加省略号*/
						}

						&>div:nth-child(2) {
							flex: 1;
							cursor: pointer;
						}
					}

					&>.item:nth-child(n) {
						border-top: none;
					}

					&>.item:nth-child(4n) {
						margin-right: 0;
					}

					&>.item:nth-child(1),
					.item:nth-child(2),
					.item:nth-child(3),
					.item:nth-child(4) {
						border-top: 1px solid #dfe6ec;
					}
				}

				.article_content {
					height: auto;
					margin-bottom: 20px;

					.contentHtml {
						padding: 20px;
						overflow: auto;
						border: 1px solid #e4e4e4;
						box-sizing: border-box;
						height: 100%;
						background: red;
					}
				}
			}

			.footerBtn {
				width: 100%;
				display: flex;
				justify-content: center;
				padding-top: 10px;
			}

			.el-button:hover,
			.el-button:focus {
				color: #000;
			}
		}
	}
}
</style>
